Vue Js Check Whether User Device in Dark or Light Mode:To check whether the user device is in dark or light mode using Vue.js, you can utilize the matchMedia method provided by the browser’s Window object. This method returns a MediaQueryList object that represents the results of a CSS media query, which can be used to detect the user’s preferred color scheme.
How can Vue Js be used to check whether a user’s device is in dark or light mode?
The Below code is a Vue.js component that checks whether the user’s device is in dark or light mode using the window.matchMedia method, which allows you to query the user’s preferred color scheme. Here’s how the code works:
- The
datamethod initializes themodeproperty toundefined. - The
mountedlifecycle hook is called after the component has been mounted on the DOM. This is where theupdateModemethod is called to set themodeproperty to either'dark'or'light'depending on whether the user’s preferred color scheme is dark or light. - The
window.matchMediamethod is used to listen for changes to the user’s preferred color scheme. When the color scheme changes, theupdateModemethod is called again to update themodeproperty accordingly. - The
beforeUnmountlifecycle hook is called when the component is about to be unmounted from the DOM. This is where the event listener for color scheme changes is removed to prevent memory leaks. - The
:classdirective binds thedark-modeorlight-modeclass to thedivelement based on the value of themodeproperty. - The
pelement displays whether the user’s device is in dark or light mode based on the value of themodeproperty.
Vue Js Check Whether User Device in Dark or Light Mode Example
<div id="app">
<div :class="mode === 'dark' ? 'dark-mode' : 'light-mode'">
<p>User Device in {{ mode === 'dark' ? 'Dark Mode' : 'Light Mode' }}</p>
</div>
</div>
<script type="module">
const app = new Vue({
el: "#app",
data() {
return {
mode: undefined,
};
},
mounted() {
this.updateMode();
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', this.updateMode);
},
beforeUnmount() {
window.matchMedia('(prefers-color-scheme: dark)').removeEventListener('change', this.updateMode);
},
methods: {
updateMode() {
this.mode = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
},
},
})
</script>
Output of Vue Js Check Whether User Device in Dark or Light Mode



